﻿package mc_lib 
{
	import flash.display.BlendMode;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import gs.TweenLite;
	/**
	 * 音效開關
	 * @author Cain
	 */
	public class Sound_Swich extends MovieClip
	{
		private var bgm:Sound;
		private var bgmcla:SoundChannel;
		private var swich:Boolean;
		private var path:String;
		public function Sound_Swich() 
		{
			setup();
		}
		[Inspectable( name = "bgm_url", type = "String", defaultValue = "" )] 
		public function set bgm_url(_url:String):void 
		{
			if (_url=="") 
			{
				throw(new Error("未輸入音樂路徑"));
			}else 
			{
				bgm = new Sound();
				try 
				{
					bgm.load(new URLRequest(_url));
					bgmcla = bgm.play();
					SWICH = true;
					TweenLite.to(bgmcla, 0, { volume:0 } );
					TweenLite.to(bgmcla, 1, { volume:1 } );
					bgmcla.addEventListener(Event.SOUND_COMPLETE, onSOUND_COMPLETE);
				}catch (err:Error)
				{
					throw(new Error("找不到路徑"));
				}
				
			}
		}
		
		private function onSOUND_COMPLETE(e:Event):void 
		{
			bgmcla = bgm.play();
			bgmcla.addEventListener(Event.SOUND_COMPLETE, onSOUND_COMPLETE);
			if (SWICH) 
			{
				TweenLite.to(bgmcla, 0, { volume:1 } );
			}else 
			{
				TweenLite.to(bgmcla, 0, { volume:0 } );
			}
		}
		private function setup():void
		{
			
			addEventListener(Event.ADDED_TO_STAGE, addthis);
		}
		
		private function addthis(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, addthis);
			addEventListener(Event.REMOVED_FROM_STAGE, renovethis);
			init();
		}
		
		private function init():void
		{
			
			addEventListener(MouseEvent.CLICK, onClick);
			cain();
		}
		
		private function cain():void
		{
			var tf:TextField = new TextField();
			Sprite(root).addChild(tf);
			tf.text = "as3 code by 朱信曄 in 雄獅旅遊 cainmaila@gmail.com";
			tf.mouseEnabled = false;
			tf.blendMode = BlendMode.LAYER;
			tf.alpha = 0;
		}
		
		private function onClick(e:MouseEvent):void 
		{
			
			if (SWICH) 
			{
				SWICH = false;
			}else 
			{
				SWICH = true;
			}
		}
		
		private function renovethis(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, renovethis);
			removeEventListener(MouseEvent.CLICK, onClick);
		}
		/**
		 * 音效關關
		 */
		public function set SWICH(_swich:Boolean):void 
		{
			if (bgm!=null) 
			{
				if (_swich) 
				{
					swich = true;
					TweenLite.to(bgmcla, 1, { volume:1 } );
					gotoAndStop(1);
				}else 
				{
					swich = false;
					TweenLite.to(bgmcla, 1, { volume:0 } );
					gotoAndStop(2);
				}
			}
			
		}
		public function get SWICH():Boolean
		{
			return swich;
		}
	}

}